import cv2

cap = cv2.VideoCapture(0)

# 读取第一帧
ret, prev_frame = cap.read()
prev_gray = cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY)

while True:
    ret, frame = cap.read()

    if not ret:
        break

    # 将当前帧转换为灰度图像
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 计算当前帧与前一帧的差异
    frame_diff = cv2.absdiff(prev_gray, gray_frame)

    # 对差异图像进行二值化处理
    _, thresh = cv2.threshold(frame_diff, 30, 255, cv2.THRESH_BINARY)

    # 显示运动检测结果
    cv2.imshow('Motion Detection', thresh)

    # 更新前一帧
    prev_gray = gray_frame

    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()